// pages/exercise/index.js
let app = getApp()

Page({
  data: {
    currentQuestion: {},
    userAnswer: '',
    questionList: [],
    currentIndex: 0,
    currentGlobalIndex: 0,
    showAnalyze: false,
    analyzeData: {},
    loading: false,
    loadingMore: false,
    hasMore: true,
    pageIndex: 1,
    pageSize: 20,
    type: '',
    status: '',
    mode: '',
    isWrong: '', // 新增 isWrong 字段
    parsedTitle: '',
    parsedOptions: [],
    totalQuestions: 0,
    jumpInputVisible: false,
    jumpQuestionNumber: '',
    jumpQuestionError: '',
    currentPage: 1,
    totalPages: 1,
    // 缓存已加载的页面数据
    pageCache: {}
  },

  onLoad: function(options) {
    const { type, status, mode, isWrong } = options
    console.log('页面参数:', options);

    this.setData({
      type: type || '',
      status: status || '',
      mode: mode || '',
      isWrong: isWrong || '' // 接收 isWrong 参数
    });

    this.loadQuestions(true);
  },

  loadQuestions: function(override) {
    if (this.data.loading) {
      console.log('正在加载中，跳过请求');
      return;
    }

    this.setData({
      loading: true
    });

    const requestParams = {
      pageIndex: override ? 1 : this.data.pageIndex,
      pageSize: this.data.pageSize
    };

    if (this.data.type) {
      requestParams.subjectId = this.data.type;
    }
    if (this.data.status) {
      requestParams.status = this.data.status;
    }
    if (this.data.isWrong) {
      requestParams.isWrong = this.data.isWrong;
    }
    console.log('请求题目参数:', requestParams);

    app.formPost('/api/wx/student/question/page', requestParams)
        .then(res => {
          this.setData({ loading: false });

          if (res.code === 1) {
            const re = res.response;
            const newList = re.list || [];
            const total = re.total || 0;
            const pages = re.pages || Math.ceil(total / this.data.pageSize) || 1;
            
            // 缓存当前页数据
            const pageCache = this.data.pageCache;
            const currentPage = override ? 1 : this.data.pageIndex;
            pageCache[currentPage] = newList;
            
            if (override) {
              // 首次加载或覆盖加载
              this.setData({
                questionList: newList,
                pageIndex: 2,
                totalQuestions: total,
                totalPages: pages,
                currentPage: 1,
                currentGlobalIndex: 0,
                pageCache: pageCache
              });

              if (newList.length > 0) {
                this.setCurrentQuestion(0);
              }
            } else {
              // 追加加载
              const combinedList = this.data.questionList.concat(newList);
              this.setData({
                questionList: combinedList,
                pageIndex: this.data.pageIndex + 1,
                totalQuestions: total,
                totalPages: pages,
                pageCache: pageCache
              });
            }

            console.log('加载成功', {
              '题目数量': newList.length,
              '总题数': total,
              '总页数': pages,
              '当前页码': override ? 1 : this.data.pageIndex
            });
          } else {
            console.error('接口返回错误:', res.message);
            wx.showToast({
              title: res.message || '加载失败',
              icon: 'none',
              duration: 2000
            });
          }
        })
        .catch(e => {
          this.setData({ loading: false });
          console.error('请求题目失败:', e);
          wx.showToast({
            title: '网络请求失败',
            icon: 'none',
            duration: 2000
          });
        });
  },

  // 加载指定页面的方法
  loadSpecificPage: function(pageNumber, callback) {
    if (this.data.loading) return;
    
    this.setData({ loading: true });
    
    const requestParams = {
      pageIndex: pageNumber,
      pageSize: this.data.pageSize
    };

    if (this.data.type) {
      requestParams.subjectId = this.data.type;
    }
    if (this.data.status) {
      requestParams.status = this.data.status;
    }
    if (this.data.isWrong) {
      requestParams.isWrong = this.data.isWrong;
    }
    console.log('加载指定页面参数:', requestParams);

    app.formPost('/api/wx/student/question/page', requestParams)
        .then(res => {
          this.setData({ loading: false });

          if (res.code === 1) {
            const re = res.response;
            const newList = re.list || [];
            
            // 更新缓存
            const pageCache = this.data.pageCache;
            pageCache[pageNumber] = newList;
            
            this.setData({
              questionList: newList,
              currentPage: pageNumber,
              pageCache: pageCache
            });

            console.log('加载指定页面成功', {
              '页码': pageNumber,
              '题目数量': newList.length
            });

            if (callback && typeof callback === 'function') {
              callback();
            }
          } else {
            console.error('加载指定页面失败:', res.message);
            wx.showToast({
              title: res.message || '加载失败',
              icon: 'none',
              duration: 2000
            });
          }
        })
        .catch(e => {
          this.setData({ loading: false });
          console.error('加载指定页面失败:', e);
          wx.showToast({
            title: '网络请求失败',
            icon: 'none',
            duration: 2000
          });
        });
  },

  setCurrentQuestion: function(index) {
    if (index < 0 || index >= this.data.questionList.length) {
      console.error('题目索引超出范围:', index, '题目总数:', this.data.questionList.length);

      if (this.data.questionList.length > 0) {
        const safeIndex = Math.max(0, Math.min(index, this.data.questionList.length - 1));
        console.warn('自动调整索引从', index, '到', safeIndex);
        index = safeIndex;
      } else {
        console.error('题目列表为空，无法设置题目');
        return;
      }
    }

    const currentQuestion = this.data.questionList[index];

    if (!currentQuestion) {
      console.error('获取题目失败，索引:', index);
      return;
    }

    // 计算全局索引（基于当前页码和页面内索引）
    const globalIndex = (this.data.currentPage - 1) * this.data.pageSize + index;

    console.log('设置题目', {
      '页面索引': index,
      '全局题号': globalIndex + 1,
      '当前页码': this.data.currentPage,
      '缓存页面': Object.keys(this.data.pageCache)
    });

    const parsedTitle = this.parseHtmlContent(currentQuestion.title);
    const parsedOptions = currentQuestion.items ? currentQuestion.items.map(item =>
        this.parseHtmlContent(item.content)
    ) : [];

    this.setData({
      currentIndex: index,
      currentGlobalIndex: globalIndex,
      currentQuestion: currentQuestion,
      userAnswer: '',
      showAnalyze: false,
      analyzeData: {},
      parsedTitle: parsedTitle,
      parsedOptions: parsedOptions
    });
  },

  parseHtmlContent: function(htmlContent) {
    if (!htmlContent || typeof htmlContent !== 'string') {
      return htmlContent || '';
    }
    return htmlContent;
  },

  onSelectAnswer: function(e) {
    const answer = e.currentTarget.dataset.answer;
    console.log('选择答案:', answer);

    if (this.data.showAnalyze) return;

    this.setData({ userAnswer: answer });
    
    // 直接显示答案
    this.checkAnswer();
  },

  checkAnswer: function() {
    const userAnswer = this.data.userAnswer;

    if (!userAnswer) {
      return;
    }

    const currentQuestion = this.data.currentQuestion;
    const isCorrect = userAnswer === currentQuestion.correct;

    console.log('验证答案 - 用户答案:', userAnswer, '正确答案:', currentQuestion.correct, '是否正确:', isCorrect);

    this.setData({
      showAnalyze: true,
      analyzeData: {
        isCorrect: isCorrect,
        correctAnswer: currentQuestion.correct
      }
    });
  },

  // 修复的上一题方法
  prevQuestion: function() {
    console.log('上一题 - 当前状态:', {
      '当前页码': this.data.currentPage,
      '当前索引': this.data.currentIndex,
      '缓存页面': Object.keys(this.data.pageCache)
    });
    
    const prevIndex = this.data.currentIndex - 1;
    
    if (prevIndex >= 0) {
      // 在当前页内上一题
      console.log('在当前页内上一题');
      this.setCurrentQuestion(prevIndex);
    } else if (this.data.currentPage > 1) {
      // 需要跨页到上一页
      const prevPage = this.data.currentPage - 1;
      console.log('需要跨页到上一页:', prevPage);
      
      // 检查是否已缓存上一页数据
      if (this.data.pageCache[prevPage]) {
        console.log('使用缓存数据加载上一页:', prevPage);
        // 使用缓存数据
        this.setData({
          questionList: this.data.pageCache[prevPage],
          currentPage: prevPage
        }, () => {
          // 跳转到上一页的最后一题
          const lastIndex = this.data.questionList.length - 1;
          console.log('跳转到上一页最后一题，索引:', lastIndex);
          this.setCurrentQuestion(lastIndex);
        });
      } else {
        console.log('加载上一页数据:', prevPage);
        // 加载上一页数据
        this.loadSpecificPage(prevPage, () => {
          // 加载完成后跳转到上一页的最后一题
          const lastIndex = this.data.questionList.length - 1;
          console.log('加载完成，跳转到上一页最后一题，索引:', lastIndex);
          this.setCurrentQuestion(lastIndex);
        });
      }
    } else {
      wx.showToast({
        title: '已经是第一题了',
        icon: 'none'
      });
    }
  },

  // 修复的下一题方法
  nextQuestion: function() {
    console.log('下一题 - 当前状态:', {
      '当前页码': this.data.currentPage,
      '当前索引': this.data.currentIndex,
      '缓存页面': Object.keys(this.data.pageCache)
    });
    
    const nextIndex = this.data.currentIndex + 1;
    
    if (nextIndex < this.data.questionList.length) {
      // 在当前页内下一题
      console.log('在当前页内下一题');
      this.setCurrentQuestion(nextIndex);
    } else if (this.data.currentPage < this.data.totalPages) {
      // 需要跨页到下一页
      const nextPage = this.data.currentPage + 1;
      console.log('需要跨页到下一页:', nextPage);
      
      // 检查是否已缓存下一页数据
      if (this.data.pageCache[nextPage]) {
        console.log('使用缓存数据加载下一页:', nextPage);
        // 使用缓存数据
        this.setData({
          questionList: this.data.pageCache[nextPage],
          currentPage: nextPage
        }, () => {
          // 跳转到下一页的第一题
          console.log('跳转到下一页第一题');
          this.setCurrentQuestion(0);
        });
      } else {
        console.log('加载下一页数据:', nextPage);
        // 加载下一页数据
        this.loadSpecificPage(nextPage, () => {
          // 加载完成后跳转到下一页的第一题
          console.log('加载完成，跳转到下一页第一题');
          this.setCurrentQuestion(0);
        });
      }
    } else {
      wx.showToast({
        title: '已经是最后一题了',
        icon: 'none'
      });
    }
  },

  showJumpInput: function() {
    this.setData({
      jumpInputVisible: true,
      jumpQuestionNumber: '',
      jumpQuestionError: ''
    });
  },

  hideJumpInput: function() {
    this.setData({
      jumpInputVisible: false
    });
  },

  onJumpInputChange: function(e) {
    const value = e.detail.value;
    this.setData({
      jumpQuestionNumber: value,
      jumpQuestionError: ''
    });
  },

  jumpToQuestion: function() {
    const questionNumber = parseInt(this.data.jumpQuestionNumber);

    if (isNaN(questionNumber) || questionNumber < 1) {
      this.setData({
        jumpQuestionError: '请输入有效的题号'
      });
      return;
    }

    if (this.data.totalQuestions > 0 && questionNumber > this.data.totalQuestions) {
      this.setData({
        jumpQuestionError: `题号不能超过总题数 ${this.data.totalQuestions}`
      });
      return;
    }

    const targetPage = Math.ceil(questionNumber / this.data.pageSize);
    const localIndex = (questionNumber - 1) % this.data.pageSize;

    console.log('跳转计算:', {
      '目标题号': questionNumber,
      '目标页码': targetPage,
      '目标局部索引': localIndex,
      '当前页码': this.data.currentPage
    });

    if (targetPage === this.data.currentPage) {
      // 在当前页内跳转
      this.setCurrentQuestion(localIndex);
      this.hideJumpInput();
    } else {
      // 跨页跳转
      this.loadSpecificPage(targetPage, () => {
        // 确保目标索引在有效范围内
        const safeIndex = Math.min(localIndex, this.data.questionList.length - 1);
        this.setCurrentQuestion(safeIndex);
        this.hideJumpInput();
      });
    }
  },

  onReachBottom: function() {
    console.log('页面触底，加载更多题目');
    if (this.data.hasMore && !this.data.loadingMore && !this.data.loading) {
      this.loadQuestions(false);
    }
  }
});